import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import '../models/mood_record.dart';
import '../models/mood_type.dart';
import '../constants/app_theme.dart';
import '../constants/app_strings.dart';

/// 情绪记录卡片组件
/// 用于在列表中显示情绪记录的摘要信息
class MoodCard extends StatelessWidget {
  /// 情绪记录
  final MoodRecord record;
  
  /// 点击回调
  final VoidCallback? onTap;
  
  /// 长按回调
  final VoidCallback? onLongPress;
  
  /// 是否显示日期
  final bool showDate;
  
  /// 是否显示时间
  final bool showTime;
  
  /// 是否显示媒体指示器
  final bool showMediaIndicator;
  
  /// 是否紧凑模式
  final bool compact;
  
  /// 编辑回调
  final VoidCallback? onEdit;
  
  /// 删除回调
  final VoidCallback? onDelete;

  const MoodCard({
    super.key,
    required this.record,
    this.onTap,
    this.onLongPress,
    this.onEdit,
    this.onDelete,
    this.showDate = true,
    this.showTime = true,
    this.showMediaIndicator = true,
    this.compact = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.white,
            record.moodType.color.withValues(alpha: 0.03),
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: record.moodType.color.withValues(alpha: 0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: record.moodType.color.withValues(alpha: 0.1),
            blurRadius: 20,
            offset: const Offset(0, 8),
            spreadRadius: 0,
          ),
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onTap,
          onLongPress: onLongPress,
          borderRadius: BorderRadius.circular(16),
          child: Container(
            padding: EdgeInsets.all(compact ? 16 : 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 头部信息
                _buildHeader(),
                
                if (!compact) ...[
                  const SizedBox(height: 16),
                  
                  // 日记内容预览
                  if (record.hasDiary) _buildDiaryPreview(),
                  
                  // 标签
                  if (record.tags.isNotEmpty) ...[
                    const SizedBox(height: 12),
                    _buildTags(),
                  ],
                  
                  // 底部信息
                  const SizedBox(height: 16),
                  _buildFooter(),
                ],
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建头部信息
  Widget _buildHeader() {
    return Row(
      children: [
        // 情绪图标
        Container(
          width: compact ? 48 : 56,
          height: compact ? 48 : 56,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                record.moodType.color.withValues(alpha: 0.2),
                record.moodType.color.withValues(alpha: 0.1),
              ],
            ),
            shape: BoxShape.circle,
            border: Border.all(
              color: record.moodType.color.withValues(alpha: 0.4),
              width: 2,
            ),
            boxShadow: [
              BoxShadow(
                color: record.moodType.color.withValues(alpha: 0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
                spreadRadius: 0,
              ),
            ],
          ),
          child: Center(
            child: Text(
              record.moodType.emoji,
              style: TextStyle(
                fontSize: compact ? 24 : 28,
              ),
            ),
          ),
        ),
        
        const SizedBox(width: 16),
        
        // 情绪信息
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 情绪名称和强度
              Row(
                children: [
                  Text(
                    record.moodType.displayName,
                    style: TextStyle(
                      fontSize: compact ? 16 : 18,
                      fontWeight: FontWeight.bold,
                      color: record.moodType.color,
                    ),
                  ),
                  const SizedBox(width: 12),
                  _buildIntensityIndicator(),
                ],
              ),
              
              const SizedBox(height: 6),
              
              // 时间信息
              _buildTimeInfo(),
            ],
          ),
        ),
        
        // 媒体指示器
        if (showMediaIndicator && record.hasMedia)
          _buildMediaIndicator(),
      ],
    );
  }

  /// 构建强度指示器
  Widget _buildIntensityIndicator() {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(5, (index) {
        return Icon(
          index < record.intensity ? Icons.circle : Icons.circle_outlined,
          size: compact ? 8 : 10,
          color: record.moodType.color.withValues(
            alpha: index < record.intensity ? 1.0 : 0.3,
          ),
        );
      }),
    );
  }

  /// 构建时间信息
  Widget _buildTimeInfo() {
    final recordDate = record.createdAt;
    String timeText;
    
    if (record.isToday) {
      timeText = showTime ? DateFormat('HH:mm').format(recordDate) : '今天';
    } else if (record.isThisWeek) {
      timeText = _getWeekdayName(recordDate.weekday);
      if (showTime) {
        timeText += ' ${DateFormat('HH:mm').format(recordDate)}';
      }
    } else {
      timeText = showDate 
          ? DateFormat('MM/dd').format(recordDate)
          : DateFormat('MM/dd HH:mm').format(recordDate);
    }
    
    return Text(
      timeText,
      style: TextStyle(
        fontSize: compact ? 11 : 12,
        color: AppTheme.textSecondaryColor,
      ),
    );
  }

  /// 构建日记预览
  Widget _buildDiaryPreview() {
    if (!record.hasDiary) return const SizedBox.shrink();
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            AppTheme.surfaceColor.withValues(alpha: 0.8),
            record.moodType.color.withValues(alpha: 0.05),
          ],
        ),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: record.moodType.color.withValues(alpha: 0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.03),
            blurRadius: 8,
            offset: const Offset(0, 2),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(6),
            decoration: BoxDecoration(
              color: record.moodType.color.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(6),
            ),
            child: Icon(
              Icons.edit_note,
              size: 16,
              color: record.moodType.color,
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              record.diarySummary,
              style: TextStyle(
                fontSize: 14,
                color: AppTheme.textPrimaryColor,
                height: 1.5,
                fontWeight: FontWeight.w500,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标签
  Widget _buildTags() {
    return Wrap(
      spacing: 8,
      runSpacing: 6,
      children: record.tags.take(3).map((tag) {
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: 12,
            vertical: 6,
          ),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                record.moodType.color.withValues(alpha: 0.15),
                record.moodType.color.withValues(alpha: 0.08),
              ],
            ),
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
              color: record.moodType.color.withValues(alpha: 0.3),
              width: 1,
            ),
            boxShadow: [
              BoxShadow(
                color: record.moodType.color.withValues(alpha: 0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
                spreadRadius: 0,
              ),
            ],
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.tag,
                size: 12,
                color: record.moodType.color,
              ),
              const SizedBox(width: 4),
              Text(
                tag,
                style: TextStyle(
                  fontSize: 12,
                  color: record.moodType.color,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  /// 构建底部信息
  Widget _buildFooter() {
    return Row(
      children: [
        // 天气信息
        if (record.weather?.isNotEmpty == true) ...[
          Icon(
            _getWeatherIcon(record.weather!),
            size: 14,
            color: AppTheme.textSecondaryColor,
          ),
          const SizedBox(width: 4),
          Text(
            record.weather!,
            style: TextStyle(
              fontSize: 12,
              color: AppTheme.textSecondaryColor,
            ),
          ),
        ],
        
        // 分隔符
        if (record.weather?.isNotEmpty == true && record.location?.isNotEmpty == true) ...[
          const SizedBox(width: 12),
          Container(
            width: 1,
            height: 12,
            color: AppTheme.dividerColor,
          ),
          const SizedBox(width: 12),
        ],
        
        // 位置信息
        if (record.location?.isNotEmpty == true) ...[
          Icon(
            Icons.location_on_outlined,
            size: 14,
            color: AppTheme.textSecondaryColor,
          ),
          const SizedBox(width: 4),
          Expanded(
            child: Text(
              record.location!,
              style: TextStyle(
                fontSize: 12,
                color: AppTheme.textSecondaryColor,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
        
        const Spacer(),
        
        // 情绪评分
        Container(
          padding: const EdgeInsets.symmetric(
            horizontal: 8,
            vertical: 4,
          ),
          decoration: BoxDecoration(
            color: _getScoreColor(record.moodScore).withValues(alpha: 0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text(
            '${record.moodScore.toStringAsFixed(1)}分',
            style: TextStyle(
              fontSize: 11,
              color: _getScoreColor(record.moodScore),
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建媒体指示器
  Widget _buildMediaIndicator() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (record.hasImages)
          Icon(
            Icons.image_outlined,
            size: 16,
            color: AppTheme.primaryColor,
          ),
        if (record.hasAudio)
          Icon(
            Icons.mic_outlined,
            size: 16,
            color: AppTheme.secondaryColor,
          ),
      ],
    );
  }

  /// 获取星期名称
  String _getWeekdayName(int weekday) {
    const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    return weekdays[weekday - 1];
  }

  /// 获取天气图标
  IconData _getWeatherIcon(String weather) {
    switch (weather) {
      case '晴天':
        return Icons.wb_sunny;
      case '多云':
        return Icons.cloud;
      case '阴天':
        return Icons.cloud_outlined;
      case '雨天':
        return Icons.umbrella;
      case '雪天':
        return Icons.ac_unit;
      default:
        return Icons.wb_cloudy;
    }
  }

  /// 获取评分颜色
  Color _getScoreColor(double score) {
    if (score >= 8) {
      return AppTheme.successColor;
    } else if (score >= 6) {
      return AppTheme.warningColor;
    } else if (score >= 4) {
      return AppTheme.infoColor;
    } else {
      return AppTheme.errorColor;
    }
  }
}

/// 紧凑型情绪卡片
/// 用于在有限空间内显示情绪记录
class CompactMoodCard extends StatelessWidget {
  /// 情绪记录
  final MoodRecord record;
  
  /// 点击回调
  final VoidCallback? onTap;

  const CompactMoodCard({
    super.key,
    required this.record,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return MoodCard(
      record: record,
      onTap: onTap,
      compact: true,
      showDate: false,
      showTime: true,
      showMediaIndicator: false,
    );
  }
}

/// 情绪卡片列表项
/// 用于在列表视图中显示情绪记录
class MoodCardListItem extends StatelessWidget {
  /// 情绪记录
  final MoodRecord record;
  
  /// 点击回调
  final VoidCallback? onTap;
  
  /// 编辑回调
  final VoidCallback? onEdit;
  
  /// 删除回调
  final VoidCallback? onDelete;
  
  /// 是否显示操作按钮
  final bool showActions;

  const MoodCardListItem({
    super.key,
    required this.record,
    this.onTap,
    this.onEdit,
    this.onDelete,
    this.showActions = false,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      child: Stack(
        children: [
          MoodCard(
            record: record,
            onTap: onTap,
            onLongPress: showActions ? null : () => _showActionSheet(context),
          ),
          
          // 操作按钮
          if (showActions)
            Positioned(
              top: 8,
              right: 8,
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (onEdit != null)
                    _buildActionButton(
                      icon: Icons.edit_outlined,
                      color: AppTheme.primaryColor,
                      onPressed: onEdit!,
                    ),
                  const SizedBox(width: 4),
                  if (onDelete != null)
                    _buildActionButton(
                      icon: Icons.delete_outlined,
                      color: AppTheme.errorColor,
                      onPressed: () => _confirmDelete(context),
                    ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButton({
    required IconData icon,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return Container(
      width: 32,
      height: 32,
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        shape: BoxShape.circle,
        border: Border.all(
          color: color.withValues(alpha: 0.3),
          width: 1,
        ),
      ),
      child: IconButton(
        icon: Icon(
          icon,
          size: 16,
          color: color,
        ),
        onPressed: onPressed,
        padding: EdgeInsets.zero,
      ),
    );
  }

  /// 显示操作菜单
  void _showActionSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16),
        ),
      ),
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              if (onEdit != null)
                ListTile(
                  leading: Icon(
                    Icons.edit_outlined,
                    color: AppTheme.primaryColor,
                  ),
                  title: Text(AppStrings.zh('common_edit')),
                  onTap: () {
                    Navigator.pop(context);
                    onEdit?.call();
                  },
                ),
              if (onDelete != null)
                ListTile(
                  leading: Icon(
                    Icons.delete_outlined,
                    color: AppTheme.errorColor,
                  ),
                  title: Text(
                    AppStrings.zh('common_delete'),
                    style: TextStyle(color: AppTheme.errorColor),
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    _confirmDelete(context);
                  },
                ),
            ],
          ),
        );
      },
    );
  }

  /// 确认删除
  void _confirmDelete(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(AppStrings.zh('common_confirm')),
          content: Text(AppStrings.zh('record_delete_confirm')),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text(AppStrings.zh('common_cancel')),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                onDelete?.call();
              },
              style: TextButton.styleFrom(
                foregroundColor: AppTheme.errorColor,
              ),
              child: Text(AppStrings.zh('common_delete')),
            ),
          ],
        );
      },
    );
  }
}